// tslint:disable
import { Component, OnInit, Input, OnDestroy } from "@angular/core";
import { ActionSheetController, AlertController, Platform } from "@ionic/angular";
import { ModalController } from "@ionic/angular";
import { Subscription } from "rxjs";
import { MessageService } from "src/app/shared/service/message.service";
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';

import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { NewBusinessInfoModalComponent } from '../new-business-info-modal/new-business-info-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { ShareFormModalComponent } from "../share-form-modal/share-form-modal.component";
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { RecommendModalComponent } from "../recommend-modal/recommend-modal.component";
import { PageModalService } from "src/app/shared/service/page-modal-service";
import { ModalFromCenterLeave, ModalFromCenterEnter } from "src/app/utils/transitions";
import { ChooseCityComponent } from "../choose-city/choose-city.component";
@Component({
  selector: 'app-single-manage-list',
  templateUrl: './single-manage-list.component.html',
  styleUrls: ['./single-manage-list.component.scss'],
})
export class SingleManageListComponent implements OnInit {
  @Input() tagData: any;
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any = { content: {} };
  currentIndex = -1;
  sessionId = localStorage.getItem("sessionId");
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "暂无数据";
  areaData = { baseName: '', distance: '', id: '', address: '', cityCode: '', areaCode: '', areaName: '', point: '' };
  positionInfo =
    {
      address: "",
      center: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).center : this.appGlobalService.defaultCityCenter,
      code: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).code : this.appGlobalService.defaultCityId,
      name: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).name : this.appGlobalService.defaultCityName,
      location: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).location : this.appGlobalService.defaultCityCenter
    };



  //  localStorage.getItem('position') ? JSON.parse(localStorage.getItem('position')).name: this.appGlobalService.defaultCityName;

  firstLink: any;
  secondLink: any;
  detailListTag: any;// 2.0 新增
  isTagAdapter = false; // 2.0 新增适配默认为false
  rightAmount = 296.56;
  showLoadMore = false;

  pageSize: number;
  pageTotal: number;

  activityMainBoxCssStyle: any;
  isGroupEnabled = false;
  groupedByDate: any;
  // 辅助方法：获取对象的键  
  groupedByDateKeys;

  expressBoxCssStyle: any;
  expressCircleCssStyle: any;
  newCirecleCssStyle: any;
  newCircleLabelCssStyle: any;
  topContentCssStyle: any;
  groupTitleCssStyle: any;
  groupBoxCssStyle: any;
  public refreshIds = new Set(); // 2024.10.16 refreshIds

  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private shareService: ShareService,
    private pageModalService: PageModalService,
    private platform: Platform,
    public modalController: ModalController) {
    // 清除订阅
    this.eventService.eventEmit.on("clearInformationHallSubscription", (obj) => {
      const reqTag = localStorage.getItem('clearInformationHallSubscriptionTag');
      localStorage.removeItem('clearInformationHallSubscriptionTag');
      if (reqTag !== undefined) {
        try {
          console.log('msg----->clear ... ');
          this.subscription.unsubscribe();
        } catch (error) {
          console.log('error----->' + JSON.stringify(error));
        }
      }
    });
  }





  async choose(item) {
    item.checked = !item.checked;
    const modal = this.modalController.getTop();
    if (modal !== undefined) {
      (await modal).dismiss({ data: this.areaData });
    }
    console.log(new Date().toLocaleString()
      + '.'
      + new Date().getMilliseconds(), item);

    const data = {
      title: item.singleGoods.secondRowLeftLabel1,
      imags: item.singleGoods.imgUrl,
      big_district: '',
      district: '',
      pluginId: item.singleGoods.pluginId,
      rentunit: item.singleGoods.thirdRowLeftLabel1,
      industry: item.singleGoods.imgTag,
      activity_reg_id: item.id
    };

    localStorage.setItem('sendSelectItemMsg', 'true');
    this.eventService.eventEmit.emit('sendSelectItemMsg', data);
  }

  ngOnInit() {

    // 2024.04.09 测试商品分类数据
    if (this.tagData && this.tagData.name && this.tagData.name === 'convenienceSupermarket') {
      return;
    }
    this.pageTotal = this.tagData.pageTotal;
    this.params = this.tagData.data.submit;
    this.pageSize = this.tagData.pageSize;
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
    // 2.0新增参数处理
    if (this.tagData && this.tagData.name && this.tagData.name.indexOf('_adapter') !== -1) {
      // console.log('admin', '...adapter');
      this.isTagAdapter = true;
      this.detailListTag = [];
      if (this.tagData.data && this.tagData.data.data && this.tagData.data.data.length > 0) {
        for (let index = 0; index < this.tagData.data.data.length; index++) {
          const element = this.tagData.data.data[index];
          if (element.buttonArray && element.buttonArray.length > 0) {
            if (element.buttonArray[0].button.submit) {
              element[element.convertBtnName] = {};
              element[element.convertBtnName]['submit'] = element.buttonArray[0].button.submit;
            }
            if (element.buttonArray[0].link) {
              element[element.convertBtnName]['link'] = {};
              element[element.convertBtnName]['link'] = element.buttonArray[0].link;
            }
          }
          this.detailListTag.push(this.createSingleDetailTag(element));
        }
      }
      // console.log('detailTag：', this.detailListTag);
    } else {
      this.isTagAdapter = false;
      if (this.tagData
        && this.tagData.data
        && this.tagData.data.headDiv
        && this.tagData.data.headDiv.buttonLinks) {
        this.firstLink = this.tagData.data.headDiv.buttonLinks[0];
        this.secondLink = this.tagData.data.headDiv.buttonLinks[1];
      }



      const listenerName = this.tagData.name + 'AskForList';
      if (this.eventService.eventEmit.listenerCount(listenerName) > 0) {
        this.eventService.eventEmit.removeListener(listenerName);
      }
      this.eventService.eventEmit.on(listenerName, (obj) => {
        this.refreshData(obj);
      });


      // 2024.01.22 新增参数用于搜索
      if (this.tagData.name.indexOf('enableSearchUpdateTagData') > -1) {
        this.eventService.eventEmit.on(this.tagData.name, (obj) => {
          // this.refreshData(obj);
          this.tagData = obj;
          if (this.params.content) {
            this.params.content = this.tagData.data.submit.content;
          }
        });
      }




      // 新增处理刷新
      if (this.tagData.name.includes('_singleData')) {
        const singleDataTagName = this.tagData.name;
        if (this.eventService.eventEmit.listenerCount(singleDataTagName) > 0) {
          this.eventService.eventEmit.removeListener(singleDataTagName);
        }
        this.eventService.eventEmit.on(singleDataTagName, (res) => {
          this.updateSingleData(res);
        });
      }


      this.params = this.tagData.data.submit;
      if (this.tagData && this.tagData.hint) {
        this.emptyDataHint = this.tagData.hint;
      }

      if (!this.subscription && this.tagData.data.submit !== undefined) {
        if (
          this.tagData.data.submit.content &&
          this.tagData.data.submit.content.showName
        ) {
          sessionStorage.setItem(
            "showName",
            this.tagData.data.submit.content.showName
          );
        } else {
          sessionStorage.removeItem("showName");
        }
        this.message.clearMessage();
        // 获取筛选参数
        this.subscription = this.message.getMessage().subscribe(param => {

          if (param === undefined) {
            return;
          } else if (param.type === 'ionRefresh') {
            this.refreshData(param);
            return;
          }
          this.pageNo = 1;
          this.params.sessionId = localStorage.getItem("sessionId");
          // 参数
          this.params.content = param;
          // 页面数据参数
          this.params.content.pageNo = this.pageNo;
          // 请求获取新数据
          this.httpService.post(
            "application/submit",
            this.params,
            res => {
              console.log("submit");
              // 请求数据成功
              if (res.success) {
                const result = res.data.data;
                // 筛选数据
                this.tagData.data.data = result;
                this.cssStyle();
                // 自动回到顶部
                setTimeout(() => {
                  const el = document.getElementById('information0');
                  if (el) {
                    el.scrollIntoView(true);
                  }

                }, 200);
              } else {
                // 请求数据失败
                this.appGlobalService.showToast(res.message, 2000, "middle");
              }
            },
            err => {
              // 请求数据失败
              this.appGlobalService.showToast(err.message, 2000, "middle");
            }
          );
        });
      }
      this.cssStyle();


      if (this.tagData.data && this.tagData.name === 'logisticsTrajectory') {
        if (this.tagData.data.data
          && this.tagData.data.data.length > 0
          && this.tagData.data.data[0].isGroupEnabled !== undefined
          && this.tagData.data.data[0].isGroupEnabled === 'true') {
          this.isGroupEnabled = true;
          if (this.tagData.data.data[0]['expressBoxCssStyle'] !== undefined) {
            this.expressBoxCssStyle = this.tagData.data.data[0]['expressBoxCssStyle'];
          }
          if (this.tagData.data.data[0]['expressCircleCssStyle'] !== undefined) {
            this.expressCircleCssStyle = this.tagData.data.data[0]['expressCircleCssStyle'];
          }
          if (this.tagData.data.data[0]['newCirecleCssStyle'] !== undefined) {
            this.newCirecleCssStyle = this.tagData.data.data[0]['newCirecleCssStyle'];
          }
          if (this.tagData.data.data[0]['newCircleLabelCssStyle'] !== undefined) {
            this.newCircleLabelCssStyle = this.tagData.data.data[0]['newCircleLabelCssStyle'];
          }
          if (this.tagData.data.data[0]['topContentCssStyle'] !== undefined) {
            this.topContentCssStyle = this.tagData.data.data[0]['topContentCssStyle'];
          }
          if (this.tagData.data.data[0]['groupTitleCssStyle'] !== undefined) {
            this.groupTitleCssStyle = this.tagData.data.data[0]['groupTitleCssStyle'];
          }
          if (this.tagData.data.data[0]['groupBoxCssStyle'] !== undefined) {
            this.groupBoxCssStyle = this.tagData.data.data[0]['groupBoxCssStyle'];
          }
          // this.tagData.data.data[1].createTime = '2024-06-20 18:00'
          const groupedByDate = this.tagData.data.data.reduce((accumulator, currentItem) => {
            let displayDate = currentItem.createTime; // .replace(/\-/g, "/");
            // let displayDate;
            // if (this.appGlobalService.isToday(date)) {
            //   displayDate = '今天';
            // } else if (this.appGlobalService.isYesterday(date)) {
            //   displayDate = '昨天';
            // } else {
            //   displayDate = this.appGlobalService.getNowFormatDateYYYYMMDD(date); // 提取月-日格式
            // }
            if (!accumulator[displayDate]) {
              accumulator[displayDate] = [];
            }
            accumulator[displayDate].push(currentItem);
            return accumulator;
          }, {});
          this.groupedByDate = groupedByDate;
          this.groupedByDateKeys = Object.keys(this.groupedByDate);

          // console.log('groupedByDate = ', this.groupedByDate);
          // this.appGlobalService.consoleLog('  	   ',Object.keys(this.groupedByDate));
        }
      }
    }
  }

  updateSingleData(param) {
    let that = this;
    let viewId = '';
    let pluginId: any;
    const page: any = JSON.parse(JSON.stringify(this.appGlobalService.getCurrentTarget()));
    if (page.params) {
    } else {
      page.params = {}
    }

    if (that.dataIndex && this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      if (this.appGlobalService.currentPartParams) {
        this.appGlobalService.consoleLog('refresh use current part params ...', '  	   ');
        page.params = JSON.parse(JSON.stringify(this.appGlobalService.currentPartParams));
      }
    }
    page['sessionId'] = localStorage.getItem('sessionId')
    if (param['keyValue'] !== undefined) {
      page[param['key']] = param['keyValue']
    } else {
      const arr = param.result.split(',');
      page[param['key']] = arr[0];
    }
    page.params['ajax'] = 'true';
    if (param['pluginId']) {
      page.params['pluginId'] = param['pluginId']
    }


    if (param['viewId']) {
      viewId = param['viewId']
      page['viewId'] = viewId;
      const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
      if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
        page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
      }

      // this.httpService.post('application/part', page, res => {
      const url = this.httpService.bathUrl + 'application/part';
      this.pageModalService.jsongetPostData(url, page, (res) => {
        try {
          const tagData = JSON.parse(res.script).tags;
          if (tagData) {
            tagData.forEach(element => {
              if (element && element.style.includes('singleManageListTag') && element.data.data.length === 1) {
                that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
              } else if (element && element.style.includes('singleManageListTag') && element.data.data.length > 1) {
                let tagDataArray = that.tagData.data.data;
                let elementDataArray = element.data.data;
                // 遍历 elementDataArray  
                elementDataArray.forEach(element => {
                  // 在 tagDataArray 中查找与当前元素 id 相同的元素  
                  let foundIndex = tagDataArray.findIndex(tagData => tagData.id === element.id);
                  if (foundIndex !== -1) {
                    // 如果找到了，就用 element 替换 tagDataArray 中对应的元素  
                    tagDataArray[foundIndex] = element;
                  }
                });
              }
            });
          }
        } catch (error) {
          console.log(error);
        }

      });
    } else {
      // 2024.08.29 无viewId则表示为submit提交
      this.appGlobalService.consoleLog('无viewId', '  	   ');
      if (this.tagData && this.tagData.data && this.tagData.data.submit) {
        this.tagData.data.submit[param.key] = param.keyValue;
      }
      this.updateItem(param);
    }
  }

  /**
   *
   * @param item 渲染页面按钮样式
   * @param dataIndex
   */
  cssStyle() {
    if (this.tagData.data && this.tagData.data.data) {
      this.tagData.data.data.forEach(data => {
        if (
          data.fourthRowLeft && data.fourthRowLeft.firstText &&
          data.fourthRowLeft.firstText.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.firstText.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstText.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTag &&
          data.fourthRowLeft.secondTag.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTag.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTag.childCss = childCss;
        }
        if (data.fourthRowLeft && data.fourthRowLeft.firstTag && data.fourthRowLeft.firstTag.cssStyle) {
          const cssStyles = data.fourthRowLeft.firstTag.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {

            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstTag.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTest &&
          data.fourthRowLeft.secondTest.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTest.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {

            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTest.childCss = childCss;
        }
      });
    }

  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


  // 分享弹框
  async presentShare58Modal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      backdropDismiss: true,
      component: ShareFormModalComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


  async presentAlertWithMsgBtn(msg, btnText, button) {
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: btnText,
          handler: () => {
            // this.httpService.changeCallNumber(mobile);
            const params = {
              content: button.submit.content,
              id: button.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                this.appGlobalService.reloadCurrentPage();
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }



  iconClick2(buttonLinks, item, event?) {
    if (event) {
      event.stopPropagation();
    }
    if (buttonLinks && buttonLinks.length > 0) {
      if (item) {
        const button = buttonLinks[0];
        this.iconClick(button);
      } else {
        return;
      }
    } else {
      return;
    }
  }

  /**
   *
   * @param item 点击图标
   */
  iconClick(item, data?, e?, index?) {
    if (e) {
      e.stopPropagation();
    }
    const that = this;

    // 2024.10.14 新增红点非实时更新
    if (item.badge !== undefined) {
      item.badge = '0';
    }

    if (item.link && item.modelType === undefined) {
      if (item.link.type === 'page') {
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      } else if (item.link.type === 'model' || item.link.type === 'modal' || item.link.type === 'pageModal') {
        this.pageModalService.openPage(item.link, '', result => {
          if (item.link.params.refresh !== undefined && !result) return;  // 说明弹窗点了取消
          else if (item.link.params.checkResult !== undefined && !result) return;
          that.updateItem(item);
        });

      } else if (item.link.type && item.link.type === 'chat') {//
        // 1.9.15 违规与投诉新增聊天参数
        if (item.link.params !== undefined && item.link.params.chatId !== undefined) {
          if (item.link.params.isChat !== undefined && item.link.params.isChat !== 'false') {

            this.httpService.gotoChat(item, item.link.params.chatId);
          } else {
            let tips = '客户未开通在线聊天账号，无法联系客户';
            if (item.link.params.tip !== undefined) {
              tips = item.link.params.tip;
            }
            this.appGlobalService.showToast(tips, 1500, 'middle');
          }

        } else {
          this.httpService.gotoChat(item);
        }
      }
    }
    else if (item.button && item.modelType === undefined) {
      if (item.action && item.action === 'question') {
        this.presentAlertWithMsgBtn(item.msg, item.text ? item.text : '确定', item.button);
      } else if (item.action && item.action === 'onlySubmit') {
        const params = {
          content: item.button.submit.content,
          id: item.button.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            that.updateItem();
            // this.tagData.data.data.splice(this.dataIndex, 1);
          }
          this.appGlobalService.showToast(res.message, 1500, "middle");
        });
      } else if (item.action && item.action === 'onlySubmitDelete') {
        const params = {
          content: item.button.submit.content,
          id: item.button.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
          this.appGlobalService.showToast(res.message, 1500, "middle");
        });

        // 1.7.1 蜂喔赚钱宝新增用于存在多个 领取的账号问题
      } else if (item.action && item.action === 'onlySubmitRefresh') {
        const params = {
          content: item.button.submit.content,
          id: item.button.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            this.appGlobalService.reloadCurrentPage();
          }
          this.appGlobalService.showToast(res.message, 1500, "middle");
        });

      } else {


        if (item.button.submit) {

          this.presentAlertWithMsgBtn1(item.button.submit);
        }

      }
    }
    else if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        // 1.9.15 违规与投诉新增聊天参数
        if (item.link.params !== undefined && item.link.params.chatId !== undefined) {
          this.httpService.gotoChat(item, item.link.params.chatId);
          return;
          // if (item.link.params.isChat !== undefined && item.link.params.isChat !== 'false') {
          //   this.httpService.gotoChat(item, item.link.params.chatId);
          // } else {
          //   let tips = '客户未开通在线聊天账号，无法联系客户';
          //   if (item.link.params.tip !== undefined) {
          //     tips = item.link.params.tip;
          //   }
          //   this.appGlobalService.showToast(tips, 1500, 'middle');
          // }

        } else {
          this.httpService.gotoChat(item);
        }

      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          this.presentShareModal(tmpShareData);
        });
      } else {
        this.pageModalService.openPage(item.link, '', result => {
          if (result) {
            that.updateItem(item);
          }
        });
      }

    }
    else if (item.modelType === "iconSubmit") {
      let submitParam;
      if (item.submit) {
        submitParam = item.submit;
      } else if (item.button) {
        submitParam = item.button.submit;
      }
      const params = {
        content: submitParam.content,
        id: submitParam.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
          if (index === 0) {
            localStorage.setItem("needRefreshTab1", "true");
          }
        }
        if (item.back !== undefined) {
          this.appGlobalService.goBack(Number(item.back));
          if (item.needRefreshTab1 !== undefined) {
            localStorage.setItem("needRefreshTab1", "true");
            this.eventService.eventEmit.emit('tab1', null);
          } else if (item.searchButtonClick) {
            this.appGlobalService.reloadCurrentPage(500);
          } else {
            this.appGlobalService.reloadCurrentPage(500);
          }
        } else if (item.refresh !== undefined) {
          this.appGlobalService.reloadCurrentPage(500);
        }
      });


    }
    else if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    else if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.name ? item.name : '');
      }
    }
    else if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    }
    else if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    else if (item.modelType === "remarkList") {

      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        this.remarkList(item);
      }
    }
    else if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    }
    else if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      }
    }
    else if (item.modelType === "downloadImage") {
      this.appGlobalService.saveImageFromUrl(item.imgUrl, item.imgName);
    }
    // 1.7.0 新增弹窗
    else if (item.modelType === 'question') {
      this.presentQuestion(item, item.msg, 0);
    }
    else if (item.modelType === 'copy') {
      let copyText = item.copyText;
      if (copyText) {
        this.shareService.copyUrl(copyText);
      }
    }



  }

  async presentQuestion(itemObj, msg, dataIndex) {
    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let submitParam;
            if (itemObj.submit) {
              submitParam = itemObj.submit;
            } else if (itemObj.button) {
              submitParam = itemObj.button.submit;
            }
            const params = {
              content: submitParam.content,
              id: submitParam.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              this.appGlobalService.showToast(res.message, 1500, "middle");
              if (res.success) {
                if (itemObj.refresh !== undefined) {
                  this.appGlobalService.reloadCurrentPage();
                } else if (itemObj.back !== undefined) { // 2.0新增返回处理
                  this.appGlobalService.goBack(Number(itemObj.back));
                  this.appGlobalService.popTarget();
                } else if (itemObj.afterSubmitAction && itemObj.afterSubmitAction === 'onlySubmitDelete') {
                  this.tagData.data.data.splice(this.dataIndex, 1);
                  if (itemObj.afterSubmitEventName !== undefined) {
                    this.eventService.eventEmit.emit(itemObj.afterSubmitEventName, '1');
                  }
                } else {
                  if (itemObj.link) {
                    const params = {
                      pageId: itemObj.link.target,
                      params: itemObj.link.params,
                      sessionId: localStorage.getItem("sessionId")
                    };
                    this.appGlobalService.goToForward(params);
                  }
                }
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async presentAlertWithMsgBtn1(submit) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {

            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                that.updateItem();

              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  remarkList(more) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );



  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      // const params = {
      //   pageId: itemObj.link.target,
      //   params: itemObj.link.params,
      //   sessionId: localStorage.getItem("sessionId")
      // };
      // this.appGlobalService.goToForward(params);
      this.pageModalService.openPage(itemObj.link);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
  }
  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      if (element.label) {
        buttons.push(element.label);
      }
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          ActionSheetService.close();
          that.iconClick(icons[buttonIndex]);
        }
      }
    );
  }
  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }
  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }
  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }
  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;

    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }
  go(item, event?, dataIndex?) {
    const that = this;
    if (dataIndex !== undefined) {
      that.dataIndex = dataIndex;
    }
    if (event !== undefined) {
      event.stopPropagation();
    }
    if (item.selectItemBack !== undefined && item.selectItemBack === 'true') {
      // 发送小区信息给表单

      const data = item;
      if (data !== undefined) {
        this.areaData = { baseName: '', distance: '', id: '', address: '', cityCode: '', areaCode: '', areaName: '', point: '' };
        if (data.firstRowLeft && data.firstRowLeft.firstText && data.firstRowLeft.firstText.label) {
          this.areaData.baseName = data.firstRowLeft.firstText.label;
        }
        if (data.firstRowLeft && data.firstRowLeft.secondText && data.firstRowLeft.secondText.label) {
          this.areaData.distance = data.firstRowLeft.secondText.label;
        }
        if (data.id) { // 唯一标识符
          this.areaData.id = data.id;
        }
        if (data.thirdRowLeft && data.thirdRowLeft.firstText && data.thirdRowLeft.firstText.label) {
          this.areaData.address = data.thirdRowLeft.firstText.label;
        }

        if (data.cityCode) { // 行政区域代码： 1101
          this.areaData.cityCode = data.cityCode;
        }

        if (data.areaCode) { // 大区域码 例如：110101
          this.areaData.areaCode = data.areaCode;
        }

        if (data.areaName) { // 大区域名称 例如：朝阳
          this.areaData.areaName = data.areaName;
        }


        if (data.point) { // 经纬度
          this.areaData.point = data.point;
        }
        // 发送
        this.eventService.eventEmit.emit('getResidentialDistrict', this.areaData);

        if (item.back) {
          if (Number(item.back) < 0) {
            const back = Math.abs(Number(item.back));
            for (let index = 0; index < back; index++) {
              this.appGlobalService.popTarget();
            }
            this.appGlobalService.goBack(Number(item.back));

          }
        } else {
          this.appGlobalService.goBack();
          this.appGlobalService.popTarget();
        }



      }

      return;

    }
    // 2.0 新增参数
    if (item.selectItemAskAction !== undefined && item.selectItemAskAction === 'true') {
      if (item.operationBtn && item.operationBtn.length > 0) {
        this.iconClick(item.operationBtn[0], item);
      }
    }
    // 新增 切换当前小区 返回首页刷新
    if (item.changeItem !== undefined && item.changeItem.submit) {
      const params = {
        content: item.changeItem.submit.content,
        id: item.changeItem.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {

          if (item.changeItem.submit.content.code !== undefined) {
            const position = JSON.parse(localStorage.getItem("position"))
            position.code = item.changeItem.submit.content.code;
            localStorage.setItem("position", JSON.stringify(position));
            // 不用处理当前定位，因为当前定位还是以客户的为准，

          }
          setTimeout(() => {
            localStorage.removeItem("ShareH5");
            if (item.changeItem.submit.content.back !== undefined) {
              localStorage.setItem("needRefreshTab1", "true");
              this.appGlobalService.goBack(Number(item.changeItem.submit.content.back));
            }
          }, 200);




        } else {
          this.appGlobalService.showToast(res.message, 1000, "bottom");
        }
      });
    }
    // this.appGlobalService.openPage(link, item.title);
    if (item.link && item.link.type && item.link.type === 'search') {
      document.getElementById('bottomSearch').click();
    } else {
      this.pageModalService.openPage(item.link);
    }
  }






  onClick(event, item) {
    if (item.phone && item.phone.value && item.phone.value.length > 0) {
      this.httpService.changeCallNumber(item.phone.value);
    } else if (item.link && item.link.link) {
      this.pageModalService.openPage(item.link.link);
    }
    if (event) {
      event.stopPropagation();
    }

  }
  pullToRefresh() {

  }
  refreshData(param, event?) {
    const that = this;
    if (param === undefined) {
      return;
    }
    if (this.params === undefined) {
      this.params = { content: {} };
    }
    this.params.content = param;
    this.params['sessionId'] = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    if (param) {
      Object.assign(this.params.content, param);
    }
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;
          this.cssStyle();

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
              this.cssStyle();
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);
  }

  openModalLink(item, label) {
    try {
      if (label === '业务中' || label === '签约中') {
        if (item && item.type === 'modal') {
          this.openNewBusinessInfoModal("recommend-modal", item);

        }
      } else {
        return;
      }

    } catch (error) {
    }
  }

  async openNewBusinessInfoModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.target,
        params: item.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData.data && tagData.data.length > 0) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: NewBusinessInfoModalComponent,
            componentProps: { tagData }
          });
          await modal.present();
          // 监听销毁的事件
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
          });
          await modal.present();
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  gotoSharePage(obj) {
    if (obj.tips) {
      this.appGlobalService.showToast(obj.tips, 2000, "middle");
      return;
    }
    if (obj && obj.label) {
      switch (obj.label) {
        case 'qq':
          this.shareService.shareQQ(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'qzone':
          this.shareService.shareQQZone(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'wechat':
          this.shareService.shareWeiXin(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'moment':
          this.shareService.shareMoments(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case '58':
          this.shareService.share58(obj);
          break;
        case 'tikTok': // 抖音
          if (obj.isInValidImgPosterSharing) {
            // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
            // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
            this.shareService.shareDouyinForInValidImg(obj.link.fieldLinkType);
          } else {
            this.shareService.shareDouyin(obj.title, obj.content, obj.imageUrls, obj.webpageUrl, obj.shareType);
          }
          break;
        case 'kwai': // 快手 https://play.google.com/store/apps/details?id=com.kwai.video&hl=zh&gl=US
          this.shareService.shareKuaishou(obj.title, obj.content, obj.imageUrl, obj.webpageUrl, obj.shareType);
          break;
        case 'copy':
          this.shareService.copyUrl(obj.webpageUrl);
          break;
        case 'savePic':
          // this.shareService.savePic();
          break;
        case 'posterSharing':
          this.shareService.posterSharing(obj.link.fieldLinkType);
          break;
        default:
          console.log('...gotoSharePage');
          break;
      }

    }
  }

  openShareModal(obj) {
    if (obj) {
      let subject = obj;
      if (obj.shareBtn && obj.shareBtn.fieldLinkType) {
        subject = obj.shareBtn.fieldLinkType;
      }
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: subject.link.target,
        params: subject.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        this.presentShareModal(tmpShareData);
      });
    }
  }

  async previewImage(imageUrl, tmpIndex, isPreview) {
    // event.stopPropagation();
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }

  }


  call(event, phone, name) {
    if (event) {
      event.stopPropagation();
    }
    this.presentAlertConfirm(Number(phone), name);
  }
  morebtnClick(moreLink, index, spliceIndex?) {
    if (!moreLink) {
      return;
    }
    let tempItem = [];
    this.dataIndex = index;
    if (spliceIndex) {
      moreLink.forEach((element, index) => {
        if (index !== 0) {
          tempItem.push(element);
        }
      });
      this.showActionSheet(tempItem);
    } else {
      this.showActionSheet(moreLink);
    }
  }
  normalBtnClick(buttonItem, index) {
    if (!buttonItem) {
      return;
    }
    this.dataIndex = index;
    this.iconClick(buttonItem);
  }




  gotoPage(obj) {
    try {
      if (obj) {
        const targetObj = { pageId: obj.target, params: obj.params, sessionId: localStorage.getItem('sessionId') };
        this.appGlobalService.goToForward(targetObj);
      }
    } catch (error) {
    }
  }

  updateItem(item?) {
    const that = this;

    if (!item && !this.tagData.data.data[that.dataIndex].id) {
      return;
    }

    let page: any = JSON.parse(JSON.stringify(this.appGlobalService.getCurrentTarget()));
    if (page && page.params) {
    } else {
      // 2023.11.23 fixed bug 
      page.params = {}
    }

    if (this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      if (this.appGlobalService.currentPartParams) {
        this.appGlobalService.consoleLog('refresh use current part params ...', '  	   ');
        page.params = JSON.parse(JSON.stringify(this.appGlobalService.currentPartParams));
      }
    }

    if (item && item.key && item.keyValue) {
      const data = this.tagData.data.data;
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        if (element[item.key] === item.keyValue) {
          if (element.updateItemType === undefined && item.updateItemType) {
            element['updateItemType'] = item.updateItemType;
          } else if (element.updateItemType && item.updateItemType) {
            element['updateItemType'] = item.updateItemType;
          }
          page.params = {}
          if (element.pageId !== undefined) {
            page.pageId = element.pageId;
            page['sessionId'] = localStorage.getItem('sessionId');
          }
          that.dataIndex = index;
          break;
        }

      }
    }



    if (item.updateItemType !== undefined && item.updateItemType === 'delete') {
      that.tagData.data.data.splice(this.dataIndex, 1);
      return;
    }

    if (this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      page.params['opportunity_opportunity_id'] = this.tagData.data.data[that.dataIndex].id;
      // 前端新增自定义刷新key
      if (this.tagData.data.data[that.dataIndex].customParamName) {
        page.params[this.tagData.data.data[that.dataIndex].customParamName]
          = this.tagData.data.data[that.dataIndex][this.tagData.data.data[that.dataIndex].customParamName];
      }
      page['viewId'] = this.tagData.data.data[that.dataIndex].viewId;
      page['sessionId'] = localStorage.getItem('sessionId');
      if (page['viewId'] && page.pageId) {
        delete page.pageId;
      }
      page.params['ajax'] = 'true';
      const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
      if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
        page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
      }
      // this.httpService.post('application/part', page, async resData => {
      const url = this.httpService.bathUrl + 'application/part';
      this.pageModalService.jsongetPostData(url, page, (resData) => {
        const tagData = JSON.parse(resData.script).tags;
        if (tagData) {
          tagData.forEach(element => {
            if ((element.style.includes('appInfoListTag') ||
              element.style.includes('singleManageListTag')) && element.data && element.data.data[that.dataIndex]) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[that.dataIndex]);
            } else if (element && element.style.includes('singleManageListTag') && element.data.data.length === 1) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
            }
          });
        }
      });
    } else {

      if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
        && that.tagData.data.data[that.dataIndex].updateItemType === 'delete') {
        that.tagData.data.data.splice(this.dataIndex, 1);
        return;
      }
      // 2024.03.18 刷新单条数据
      if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
        && that.tagData.data.data[that.dataIndex].updateItemType === 'updateIndexItem') {
        page.params['opportunity_opportunity_id'] = this.tagData.data.data[that.dataIndex].id;
        page.params['id'] = this.tagData.data.data[that.dataIndex].id;
        const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
        if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
          page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
        }
        // this.httpService.post('application/page', page, async res => {
        const url = this.httpService.bathUrl + 'application/page';
        this.pageModalService.jsongetPostData(url, page, (res) => {
          const tagData = JSON.parse(res.script).views[0].tags;
          tagData.forEach(element => {
            if ((element.style === 'singleManageListTag' || element.name === 'singleManageListTag')
              && element.data) {
              element.data.data.forEach(e => {
                if (e.id === that.tagData.data.data[that.dataIndex].id) {
                  that.tagData.data.data.splice(that.dataIndex, 1, e);
                  return;
                }
              })
                ;
            }
          });
        });
        return;
      }

      if (this.tagData.data.data[that.dataIndex].id) {
        page.params.id = that.tagData.data.data[that.dataIndex].id;
        const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
        if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
          page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
        }
        // this.httpService.post('application/page', page, async res => {
        const url = this.httpService.bathUrl + 'application/page';
        this.pageModalService.jsongetPostData(url, page, (res) => {
          const tagData = JSON.parse(res.script).views[0].tags;
          tagData.forEach(element => {
            if (element.style === 'singleManageListTag' && element.data && element.data.data[0]) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
            }
          });
        });
      }
    }

  }

  copyStr(e, str) {
    if (str === undefined) {
      return;
    }
    this.appGlobalService.copyStr(e, str, str);
  }

  async goBack(type) {
    if (type === 'page') {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    } else if (type === 'modal') {
      const modal = this.modalController.getTop();
      if (modal !== undefined) {
        (await modal).dismiss({ data: this.areaData });
      }
    }

  }


  async changeCity(item, event?) {
    if (event !== undefined) {
      event.stopPropagation();
    }
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: item.link.target, noStorage: true, entryType: 1, modalTitle: "选择城市" }, //    首页是1 默认不传或者0
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      if (value !== undefined && value !== undefined) {
        if (value.name) {
          this.positionInfo = value;
          const targetObj = JSON.parse(localStorage.getItem('targetObj'));
          if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
            targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
            if (targetObj.forward && targetObj.forward.params && targetObj.forward.params.code) {
              targetObj.forward.params.code = this.positionInfo.code;
              targetObj.forward.params.cityCode = this.positionInfo.code;
              targetObj.forward.params.latitude = this.positionInfo.center.lat;
              targetObj.forward.params.longitude = this.positionInfo.center.lng;
              localStorage.setItem('targetObj', JSON.stringify(targetObj));
            }
          }
          this.appGlobalService.reloadCurrentPage();
        }
      }
    });
    return await modal.present();
  }

  ngOnDestroy(): void {
    if (this.tagData && this.refreshIds) {
      this.refreshIds.forEach(element => {
        this.eventService.removeCustomListListenersByName(element);
      });
    }
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }


  createSingleDetailTag(data) {
    return { type: "tag", style: "tag.AppSimpleDetailTagLogic", name: "app-simple-detail-tag", linearLayout: "body", data };
  }


  ngAfterViewInit(): void {
    let that = this;
    // 2023.12.08 是否存在刷新控件
    if (that.tagData
      && that.tagData.data
      && that.tagData.data.data
      && that.tagData.data.data.length > 0) {
      // 2023.12.08 配置了某个属性才检查是否有下拉刷新事件
      if (that.tagData.data.data[0].isShowRefresher === 'true') {
        const debouncedHandler = that.appGlobalService.debounce((data: any) => {
          if (that.tagData.refreshId !== undefined) {
            that.eventService.eventEmit.emit(that.tagData.refreshId, '1');
          }
        }, 300);
        that.eventService.eventEmit.on('checkListIsShowRefresher', debouncedHandler);
        if (that.tagData.refreshId !== undefined) {
          that.tagData.refreshId += 'a';
          that.refreshIds.add(that.tagData.refreshId);
          console.log('init list name success!', that.tagData.refreshId);
          const debouncedHandler2 = that.appGlobalService.debounce((data: any) => {
            let tempRefresher = true;
            if (tempRefresher) {
              tempRefresher = false;
              let tempParamsContent = {};
              if (!that.params) {
                that.params = { content: {} };
                if (that.tagData.data.submit.content) {
                  that.params.content = that.tagData.data.submit.content;
                }
              } else {
                if (that.params && that.params.content) {
                  tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
                }
              }
              // that.refreshListData(tempParamsContent);
              that.refreshData(tempParamsContent);
              setTimeout(() => {
                tempRefresher = true; //防止2秒内重复请求
              }, 2000);
            }
          }, 300);
          that.eventService.eventEmit.on(that.tagData.refreshId, debouncedHandler2);
        }
      }
    }
  }

  getInterger(value) {
    return parseInt(value);
  }


  // 左边大类点击
  itemLeftClick(it) {
    this.tagData.data.data.forEach(element => {
      element.open = false;
    });
    it.open = true;
    this.tagData.current = it;
  }
  tagClick(tag) {
    if (this.tagData.data &&
      this.tagData.data.link &&
      this.tagData.data.link.params &&
      this.tagData.data.link.params.selectItemBack &&
      this.tagData.data.link.params.selectItemBack === "true") {

      this.eventService.eventEmit.emit('selectService', tag);
      this.appGlobalService.goBack();
      this.appGlobalService.popTarget();
    } else
      if (this.tagData.data && this.tagData.data.link && this.tagData.data.formKey) {
        if (this.tagData.data.link.params) {
          this.tagData.data.link.params[this.tagData.data.formKey] = tag.code;
        } else {
          this.tagData.data.link.params = { [this.tagData.data.formKey]: tag.code };
        }
        if (this.tagData.data.link.type === undefined) {
          tag.link.type = 'page'; // 防止后端返回异常数据
        }
        this.pageModalService.openPage(this.tagData.data.link);
      } else if (this.tagData.data && tag && tag.link) {
        if (tag.link.type === undefined) {
          tag.link.type = 'page'; // 防止后端返回异常数据
        }
        if (tag.link.params) {
          tag.link.params[this.tagData.data.formKey] = tag.code;
        } else {
          tag.link.params = { [this.tagData.data.formKey]: tag.code };

        }
        this.pageModalService.openPage(tag.link);

      } else if (this.tagData.data && this.tagData.data.submit && this.tagData.data.submit.params
        && this.tagData.data.submit.params.code !== undefined && this.tagData.data.submit.params.parent_id !== undefined) {
        this.tagData.data.submit.params.code = tag.code;
        this.tagData.data.submit.params.parent_id = this.tagData.current.code;

        const params = {
          content: this.tagData.data.submit.params,
          id: this.tagData.data.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };

        this.httpService.post("application/submit", params, res => {

          if (res.success && res.target) {

            if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
              res.params[res.params.eventResult] = res.data.eventResult;
            }
            let type = res.type ? res.type : 'page';
            if (res.skip === 1) {
              type = 'page';
            } else if (res.skip === 4) {
              type = 'pageModal';
            }
            // tslint:disable-next-line:no-shadowed-variable
            const link = {
              type,
              target: res.target,
              params: res.params ? res.params : {}
            };
            this.pageModalService.openPage(link);

          }
        });
      } else {
        this.pageModalService.openPage(tag.link);
      }

  }

  jump(link) {
    if (link && link.target) {
      this.pageModalService.openPage(link);
    }
  }

  addToCart(tag) {
  }

  isLabelString(label: any): boolean {
    return typeof label === 'string';
  }

  isLabelArray(label: any): boolean {
    return Array.isArray(label);
  }
}
